import {
    switchUserCompany,
    getCompanyBalance
} from '../../../../api/app.js'
import {
    getExamineInfo,
    approval,
    getQueryCompanyPayPlatform,
    checkTotalMoneySumApi
} from '../../../api/pay'
import {
    inputchange
} from '../../../../utils/util'
import user from '../../../../utils/user'

const app = getApp()
Page({
    data: {
        paymentAmountCap: '',
        isExcessPriceUp: false,
        cueMsg: '',
        payPlanInfo: {},
        currentType: 0,
        isup: false,
        data: {},
        companyName: '',
        refuseStatus: false,
        refuseText: '',
        confirmStatus: false,
        confirmText: '',
        options: {},
        getPasswordStatus: false,
        userId: '',
        isSuperAdmin: '', // 拿到是否是超管标识
        isAdmin: '', // 拿到是否是管理员标识,
        rechargeStatus: false,
        balance: 0, // 公司余额,
        balanceRemind: 0,
        isPlacard: true
    },
    onCloseExcessPriceUp() {
        this.setData({
            isExcessPriceUp: false
        })
    },
    async onBreakExcessPrice() {
        await this.onCloseExcessPriceUp()
        this.setData({
            confirmStatus: true
        })
    },
    onLoad(options) {
        this.setData({
            'options': options,
            userId: user.userId,
        })
        user.waitLogin().then(() => {
            this.setData({
                isSuperAdmin: user.isSuperAdmin,
                isAdmin: user.isAdmin
            })
        })
    },
    onChangeType(e) {
        let i = e.currentTarget.dataset.i
        if (!this.data.payPlanInfo.isOpenAlipay && i === 2) {
            wx.showToast({
                title: '支付宝账户未开通',
                icon: 'none'
            })
            return
        }
        if (!this.data.payPlanInfo.isOpenWx && i === 1) {
            wx.showToast({
                title: '微信账户未开通',
                icon: 'none'
            })
            return
        }
        if (this.data.payPlanInfo.isHaveAdvance && i === 2) {
            wx.showToast({
                title: '预支单暂不支持支付宝',
                icon: 'none'
            })
            return
        }
        this.setData({
            currentType: i
        })
    },
    closepopup() {
        this.setData({
            isup: false,
            confirmText: ''
        })
    },
    onShow: function () {
        console.log('回到页面是否执行', this.data.getPasswordStatus)
        if (this.data.getPasswordStatus) {
            this.setData({
                getPasswordStatus: false
            })
            return 0
        }
        const options = this.data.options
        user.waitLogin().then(() => {
            if (options.companyId && options.companyId !== user.companyId) {
                switchUserCompany({
                    companyId: options.companyId,
                    userId: user.userId
                }).then(() => {
                    user.reLogin().then(() => {
                        this.getExamineInfo(options.id)
                    })
                })
            } else {
                this.getExamineInfo(options.id)
            }
            getCompanyBalance({
                companyId: user.companyId
            }).then(res => {
                this.setData({
                    balance: res.availableAmount,
                    balanceRemind: user.balanceRemind
                })
            })
        })
    },
    getExamineInfo(id) {
        getExamineInfo({
            id: id,
            userId: user.userId,
            companyId: user.companyId
        }).then(res => {
            this.setData({
                data: res,
                companyName: user.companyName
            })
        })
    },
    onInputChange(event) {
        inputchange(event, this)
    },
    // 申请  type 0取消 1同意 2驳回
    approval(type, content = '', password) {
        return approval({
            payAccountFlag: this.data.currentType === 1 ? '10001' : '20001',
            id: this.data.data.id,
            params: {
                isAgree: type,
                approverId: user.userId,
                auditContent: content,
                password
            }
        })
    },
    // 取消申请
    onCancelApply() {
        app.confirm('是否取消申请？').then(() => {
            this.approval(0).then(res => {
                console.log(res, 'res返回值')
                app.toast('取消申请成功')
                setTimeout(() => {
                    wx.navigateBack()
                }, 1000)
            })
        })
    },
    // 修改重新提交
    onReApply() {
        wx.navigateTo({
            url: '/packagePay/pages/pay-wage/pay-wage?id=' + this.data.data.projectId + '&type=' + this.data.data.projectType + '&processId=' + this.data.options.id
        })
    },
    onRefuse() {
        this.setData({
            refuseStatus: true
        })
    },
    onCancelRefuse() {
        this.setData({
            refuseStatus: false
        })
    },
    onSubmitRefuse() {
        if (!this.data.refuseText) {
            app.toast('请输入驳回原因')
            return 0
        }
        this.approval(2, this.data.refuseText || '驳回').then(() => {
            wx.navigateTo({
                url: '/pages/success/success?title=驳回成功&opinion=1&back=2&type=1'
            })
        })

    },
    async onConfirm() {
        let checkArr = []
        checkArr.push({
            serveCompanyId: this.data.data.serveCompanyId,
            totalMoney: this.data.data.totalMoney,
        })
        console.log(checkArr, 'guyfsdguyhsdguyh')
        let res = await checkTotalMoneySumApi({
            checkTotalMoneySumParamList: checkArr
        })
        console.log(res, 'sdfhuiiuhsdghuigsuih')
        if (res.serveCompanyIds?.length > 0) {
            this.setData({
                isExcessPriceUp: true,
                paymentAmountCap: res.paymentAmountCap,
                cueMsg: res.cueMsg,
            })
            return
        }
        // console.log(user.balanceRemind, (this.data.balance - this.data.data.totalMoney))
        // const userId = this.data.data.approveDetails[this.data.data.approveDetails.length - 1].userId // 拿到审批流最后一个人的userId

        // if ((this.data.balance - this.data.data.totalMoney) < user.balanceRemind && this.data.balanceRemind !== 0 && userId == user.userId) {
        //     this.setData({
        //         rechargeStatus: true
        //     })
        //     console.log('当前余额不足')
        //     return
        // }
        this.setData({
            confirmStatus: true
        })
    },
    onCancelConfirm() {
        this.setData({
            confirmStatus: false
        })
    },
    onEndSubmit() {
        if (this.data.currentType !== 0) {
            const userId = this.data.data.approveDetails[this.data.data.approveDetails.length - 1].userId // 拿到审批流最后一个人的userId
            if (this.data.currentType === 1 && (this.data.payPlanInfo.wxCanUseBalance - this.data.data.totalMoney) < user.balanceRemind && this.data.balanceRemind !== 0 && userId == user.userId) {
                this.setData({
                    rechargeStatus: true
                })
                console.log('当前余额不足')
                return
            }
            if (this.data.currentType === 2 && (this.data.payPlanInfo.alpayCanUseBalance - this.data.data.totalMoney) < user.balanceRemind && this.data.balanceRemind !== 0 && userId == user.userId) {
                this.setData({
                    rechargeStatus: true
                })
                console.log('当前余额不足')
                return
            }
            wx.navigateTo({
                url: '/pages/password/password?type=get',
                events: {
                    submit: (password) => {
                        this.setData({
                            getPasswordStatus: true
                        })
                        setTimeout(() => {
                            this.approval(1, this.data.confirmText || '同意', password).then(() => {
                                this.setData({
                                    confirmStatus: false,
                                    confirmText: ''
                                })
                                wx.navigateTo({
                                    url: '/pages/success/success?title=发薪成功&opinion=1&back=2&type=1'
                                })
                            })
                        }, 100)
                    }
                }
            })
        } else {
            wx.showToast({
                title: '请选择支付方式',
                icon: 'none'
            })
        }

    },
    onSubmitConfirm() {
        if (this.data.data.isEnd) {
            // if (this.data.confirmText !== '') {
            getQueryCompanyPayPlatform({
                ids: this.data.options.id
            }).then((res) => {
                this.setData({
                    payPlanInfo: res,
                    confirmStatus: false,
                    isup: true,
                })
            })
            // } else {
            //     wx.showToast({
            //         title: '请输入原因',
            //         icon: 'none'
            //     })
            // }
            return
        }
        this.approval(1, this.data.confirmText || '同意').then(() => {
            wx.navigateTo({
                url: '/pages/success/success?title=审批成功&opinion=1&back=2'
            })
        })
    },
    onGoWorkerList() {
        wx.navigateTo({
            url: '/packagePay/pages/examine/workers/workers?id=' + this.data.options.id + '&type=' + this.data.data.projectType
        })
    },
    // 取消充值弹窗
    onCancelRecharge() {
        this.setData({
            rechargeStatus: false
        })
    },
    // 确定去充值
    onDetermineRecharge() {
        console.log('确定去充值')
        wx.navigateTo({
            url: '/packagePay/pages/recharge/index/index',
        })
    },
    // 提醒老板充值
    onShareAppMessage() {
        return {
            title: '发薪余额不足',
            path: '/packagePay/pages/recharge/index/index',
            imageUrl: '/packagePay/assets/img/remind-recharge.png'
        }
    },
    // 关闭垫资提示
    onCloneTipsPlacard() {
        this.setData({
            isPlacard: false
        })
    },
    // 跳转到垫资页面
    onGoAdvancePayment() {
        wx.navigateTo({
            url: '../../../../packageActivity/pages/advance-payment/advance-payment',
        })
    }
})